package sfms.view;

import java.io.*;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import sfms.util.DBLocation;
import sfms.util.DirectoryCopier;

public class Admin extends javax.swing.JFrame {

    java.util.Date minDate = new java.util.Date();
    private sfms.controller.Admin controller;
    
    
    public Admin(sfms.controller.Admin controller) {
        initComponents();
        this.controller = controller;
        setLocationRelativeTo(null);
        
        addHooks();       
    }
    
    void createUser(String username, String fname, String lname, String email, String number, String role, boolean active, java.sql.Date expiry, String password) {
        controller.createUser(username, fname, lname, role, active, number, email, expiry, password);
        controller.addUsers();
    }
    
    /**
     * Adds the hooks for the controller
     */
    private void addHooks() {
        controller.setBookingModel((DefaultTableModel) tableUsers.getModel());
        buttonDeleteUser.addActionListener(controller.getDeleteUserListener());
        controller.addUsers();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cMainPanel = new javax.swing.JPanel();
        panelAdmin = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tableUsers = new javax.swing.JTable();
        titleLabel = new javax.swing.JLabel();
        buttonCreateUser = new javax.swing.JButton();
        buttonEditUser = new javax.swing.JButton();
        buttonDeleteUser = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        menuFile = new javax.swing.JMenu();
        itemLogout = new javax.swing.JMenuItem();
        itemExit = new javax.swing.JMenuItem();
        menuSettings = new javax.swing.JMenu();
        itemChangePassword = new javax.swing.JMenuItem();
        itemBackupData = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Sports Facility Management System");
        setMinimumSize(new java.awt.Dimension(640, 480));
        setName("MainWindow"); // NOI18N

        cMainPanel.setLayout(new java.awt.BorderLayout());

        tableUsers.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Username", "First name", "Last name", "Email", "Role", "Phone"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tableUsers.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tableUsers.getTableHeader().setReorderingAllowed(false);
        jScrollPane3.setViewportView(tableUsers);
        tableUsers.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        titleLabel.setFont(new java.awt.Font("Lucida Grande", 0, 36)); // NOI18N
        titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        titleLabel.setText("Manage Users");

        buttonCreateUser.setText("Create New User");
        buttonCreateUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCreateUserActionPerformed(evt);
            }
        });

        buttonEditUser.setText("Edit User");
        buttonEditUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonEditUserActionPerformed(evt);
            }
        });

        buttonDeleteUser.setText("Delete User");
        buttonDeleteUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonDeleteUserActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelAdminLayout = new javax.swing.GroupLayout(panelAdmin);
        panelAdmin.setLayout(panelAdminLayout);
        panelAdminLayout.setHorizontalGroup(
            panelAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelAdminLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelAdminLayout.createSequentialGroup()
                        .addComponent(buttonDeleteUser, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(buttonCreateUser, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonEditUser, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(titleLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 647, Short.MAX_VALUE))
                .addContainerGap())
        );
        panelAdminLayout.setVerticalGroup(
            panelAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelAdminLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(titleLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelAdminLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonEditUser)
                    .addComponent(buttonCreateUser)
                    .addComponent(buttonDeleteUser))
                .addContainerGap())
        );

        cMainPanel.add(panelAdmin, java.awt.BorderLayout.CENTER);

        menuFile.setText("File");

        itemLogout.setText("Log Out");
        itemLogout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemLogoutActionPerformed(evt);
            }
        });
        menuFile.add(itemLogout);

        itemExit.setText("Exit");
        itemExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemExitActionPerformed(evt);
            }
        });
        menuFile.add(itemExit);

        menuBar.add(menuFile);

        menuSettings.setText("Settings");

        itemChangePassword.setText("Change Password");
        itemChangePassword.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemChangePasswordActionPerformed(evt);
            }
        });
        menuSettings.add(itemChangePassword);

        itemBackupData.setText("Backup Database");
        itemBackupData.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemBackupDataActionPerformed(evt);
            }
        });
        menuSettings.add(itemBackupData);

        menuBar.add(menuSettings);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(cMainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(cMainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void itemExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemExitActionPerformed
       dispose();
       System.exit(0);
    }//GEN-LAST:event_itemExitActionPerformed

    private void buttonCreateUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCreateUserActionPerformed
        AdminCreateUser createUser = new AdminCreateUser(this, true, controller);
        createUser.setVisible(true);
    }//GEN-LAST:event_buttonCreateUserActionPerformed

    private void buttonDeleteUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDeleteUserActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_buttonDeleteUserActionPerformed

    private void itemLogoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemLogoutActionPerformed
        controller.logout();
    }//GEN-LAST:event_itemLogoutActionPerformed

    private void buttonEditUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonEditUserActionPerformed
        controller.editUser(false, (String) tableUsers.getValueAt(tableUsers.getSelectedRow(), 0));
    }//GEN-LAST:event_buttonEditUserActionPerformed

    private void itemBackupDataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemBackupDataActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            File f = fc.getSelectedFile();
            
            if (DirectoryCopier.copy(DBLocation.getLocation(), f.getAbsolutePath())) {
                JOptionPane.showMessageDialog(null, "The backup was successful.");
            }
        }
    }//GEN-LAST:event_itemBackupDataActionPerformed

    private void itemChangePasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemChangePasswordActionPerformed
        try {
            String password = ChangePassword.getPassword();
            if (ChangePassword.getLastError() != null) {
                JOptionPane.showMessageDialog(this, ChangePassword.getLastError(), "Error", JOptionPane.ERROR_MESSAGE);
            } else {
                if (controller.changePassword(password)) {
                    JOptionPane.showMessageDialog(this, "Your password has been changed.", "Success", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(this, new String[]{"Your password was not changed. Please", "ensure your password was entered correctly."}, "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        } catch (Exception e) {}
    }//GEN-LAST:event_itemChangePasswordActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCreateUser;
    private javax.swing.JButton buttonDeleteUser;
    private javax.swing.JButton buttonEditUser;
    private javax.swing.JPanel cMainPanel;
    private javax.swing.JMenuItem itemBackupData;
    private javax.swing.JMenuItem itemChangePassword;
    private javax.swing.JMenuItem itemExit;
    private javax.swing.JMenuItem itemLogout;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenu menuFile;
    private javax.swing.JMenu menuSettings;
    private javax.swing.JPanel panelAdmin;
    private javax.swing.JTable tableUsers;
    private javax.swing.JLabel titleLabel;
    // End of variables declaration//GEN-END:variables

    public int getUserRow() {
        return tableUsers.getSelectedRow();
    }
}
